﻿using System;
using System.Collections.Generic;
using System.Text;
using SyncCommon;
using System.Text.RegularExpressions;
using System.IO;
using System.Web;

namespace SyncWebSite
{
    /// <summary>
    /// 超级经济人
    /// </summary>
    public class SyncMySupa : SyncHouseBase
    {
        private string cd;
        private string ptk;
        private string targetID = "";
        private string logintime = "1346058712095";
        private List<string> retImages = new List<string>();
        private List<string> retImagesUrl = new List<string>();
        private Dictionary<string, string> sortFiled = new Dictionary<string, string>();
        private Dictionary<string, string> loginCookies = new Dictionary<string, string>();
        private string CityID = "2";
        private string CityShort = "sh";
        private Encoding inputCoding = Encoding.UTF8;
        private Encoding outputCoding = Encoding.GetEncoding("GB2312");
        private string addInfo = "";
        public SyncMySupa(string user, string password)
            : base(user, password)
        {

        }

        #region SyncHouseBase

        public override bool CheckLogin()
        {
            string fieldValue = ((DateTime.Now.ToFileTime() - Convert.ToDateTime("1970-01-01").ToFileTime()) / 10000).ToString();

            WebRequest request = new WebRequest("http://login.mysupa.com/loginOrOut", FormType.FormUrlEncode, inputCoding, outputCoding);
            request.AllowRedirect = false;
            request.Cookies = loginCookies;
            request.SetHeaderValue("refer", "http://login.mysupa.com/login/");

            request.AddContent("method", "login");
            request.AddContent("caccount", UserName);
            request.AddContent("cpassword", Password);
            request.AddContent("now", fieldValue);
            string ret = request.SendWaitString();


            if (ret != "-1")
            {
                return true;
            }

            return false;
        }


        public override bool AddSaleHouse(HouseInfo info, ref string targetID)
        {
            UpdateCurrentStatus(StandardProgress.InitalData);
            //GetCityName(info);
            sortFiled.Clear();
            string error = "";
            try
            {
                //http://admin.mysupa.com/propertyNew/loadPropJournal.do?salesType=S
                if (!CheckLogin())
                {
                    UpdateCurrentStatus(StandardProgress.Failed, "登录失败");
                    return false;
                }
                else
                {
                    string errorInfor = "";
                    if (!CommonCheck(info, true, ref errorInfor))
                    {
                        UpdateCurrentStatus(StandardProgress.Failed, errorInfor);
                        return false;
                    }
                    GetCityID(info.City);
                    //http://admin.mysupa.com/evoprop/createPropJournalInit.do?salesType=S
                    WebRequest request = new WebRequest("http://admin.mysupa.com/evoprop/createPropJournalInit.do?salesType=S");
                    request.Cookies = loginCookies;
                    string ret = request.GetResouceStr();

                    request = new WebRequest("http://admin.mysupa.com/evoprop/createPropJournal.do", FormType.FormUrlEncode, Encoding.UTF8, Encoding.GetEncoding("GB2312"));
                    request.SetHeaderValue("Referer", "http://admin.mysupa.com/evoprop/createPropJournalInit.do?salesType=S");
                    request.SetHeaderValue("", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                    request.Cookies = loginCookies;
                    request.Cookies["Hm_lvt_413e31eb64ce7d19ba4cf37ed4bd0f7e"] = "1347452442161,1347460494287,1347464082841,1347538410182";
                    request.Cookies["__utma"] = "226206277.1753385560.1347375197.1347464083.1347538410.6";
                    request.Cookies["__utmz"] = "226206277.1347538410.6.3.utmcsr=baidu|utmccn=(organic)|utmcmd=organic|utmctr=%E8%B6%85%E7%BA%A7%E7%BB%8F%E7%BA%AA%E4%BA%BA";
                    request.Cookies["userSid"] = "87623606522119021736606";
                    request.Cookies["key"] = CityID;
                    //request.Cookies.Add("mysessionidup", "6fca8c80-2dd5-414a-bb10-35ecc62b9264192.168.30.73");
                    request.Cookies["Hm_lpvt_413e31eb64ce7d19ba4cf37ed4bd0f7e"] = "1347538590146";
                    request.Cookies["__utmb"] = "226206277.5.10.1347538410";
                    request.Cookies["__utmc"] = "226206277";
                    MapUserID(request, ret);
                    if (BuildingMapping(request, info, true, ret))
                    {
                        // string content = request.SendWaitString();
                        FillPostData(request, info, true);
                        UpdateCurrentStatus(StandardProgress.PosData);
                        FillSortedField(info, request);
                        string content = request.SendWaitString();
                        targetID = GetTargetID(content);


                        if (string.IsNullOrEmpty(targetID))
                        {
                            UpdateCurrentStatus(StandardProgress.Failed, "房源发布失败!");
                            return false;
                        }
                        else
                        {
                            SyncImage(info, targetID);
                            string downUrl = "http://admin.mysupa.com/evoimg/saveImageUpload.do?subType=2&journalId=" + targetID;
                            request = new WebRequest(downUrl, FormType.FormUrlEncode);
                            request.SetHeaderValue("Referer", "http://admin.mysupa.com/evoimg/imageUpload.do?journalId=" + targetID);
                            request.AllowRedirect = false;
                            request.Cookies = loginCookies;
                            request.AddContent("videoId", "0");
                            request.AddContent("photoId", "1");
                            if (retImagesUrl.Count > 0)
                            {
                                request.AddContent("coverImage", retImagesUrl[0]);
                            }
                            else
                            {
                                request.AddContent("coverImage", "");
                            }
                            request.AddContent("delImg", "");

                            request.AddContent("textValue", "");
                            request.AddContent("images1", "");
                            request.AddContent("images3", "");
                            string img5 = "";
                            foreach (string img in retImages)
                            {
                                img5 = img5 + img + ":室内图,";
                            }
                            request.AddContent("img5", string.IsNullOrEmpty(img5) ? "0" : img5);
                            request.AddContent("img1", "0");
                            request.AddContent("img3", "0");
                            request.SendWaitString();
                            request = new WebRequest(request.TransferLocation);
                            request.Cookies = loginCookies;
                            ret = request.GetResouceStr();
                            if (ret.Contains("房源发布成功"))
                            {
                                UpdateCurrentStatus(StandardProgress.Sucess, GetImageError(info), targetID, "http://" + CityShort + ".item.mysupa.com/property/" + targetID + ".html");
                                return true;
                            }
                            else
                            {
                                UpdateCurrentStatus(StandardProgress.Failed, "房源发布失败", targetID, "");
                                return false;
                            }

                        }
                    }
                    else
                    {
                        UpdateCurrentStatus(StandardProgress.Failed, "匹配小区信息失败");
                        return false;
                    }
                }
            }
            catch (System.Net.WebException exp)
            {
                error = WebError;
            }
            catch (Exception exp)
            {
                LogCenter.Log("超级经纪人信息提交", exp);
                error = exp.Message;
            }
            UpdateCurrentStatus(StandardProgress.Failed, error);
            return false;
        }

        private void FillSortedField(HouseInfo info, WebRequest request)
        {

            request.AddContent("propJournal.propRelation.estateId", sortFiled["propJournal.propRelation.estateId"]);
            request.AddContent("propJournal.status", sortFiled["propJournal.status"]);
            request.AddContent("propJournal.salesType", sortFiled["propJournal.salesType"]);
            request.AddContent("propJournal.userId", sortFiled["propJournal.userId"]);
            request.AddContent("propJournal.propRelation.areaId", sortFiled["propJournal.propRelation.areaId"]);
            request.AddContent("propJournal.propRelation.subAreaId", sortFiled["propJournal.propRelation.subAreaId"]);
            request.AddContent("propJournal.propJourExt.configure", sortFiled["propJournal.propJourExt.configure"]);
            request.AddContent("propJournal.rentPrice", sortFiled["propJournal.rentPrice"]);
            request.AddContent("propJournal.salePrice", sortFiled["propJournal.salePrice"]);
            request.AddContent("bakPropertyType", sortFiled["bakPropertyType"]);
            request.AddContent("stopComUse", sortFiled["stopComUse"]);
            request.AddContent("cityId", sortFiled["cityId"]);
            request.AddContent("avgPrice", sortFiled["avgPrice"]);
            request.AddContent("plotFlag", sortFiled["plotFlag"]);

            request.AddContent("jumpKey", sortFiled["jumpKey"]);
            request.AddContent("propJournal.propertyType", sortFiled["propJournal.propertyType"]);
            request.AddContent("propJournal.propertyName", sortFiled["propJournal.propertyName"]);
            request.AddContent("propJournal.address", sortFiled["propJournal.address"]);
            request.AddContent("propJournal.builtArea", sortFiled["propJournal.builtArea"]);

            if (info.TradeType == TradeType.Sale)
            {
                request.AddContent("temp_salePrice", sortFiled["temp_salePrice"]);
            }
            else
            {
                request.AddContent("temp_rentPrice", sortFiled["temp_rentPrice"]);
            }


            request.AddContent("propJournal.priceType", sortFiled["propJournal.priceType"]);

            if (info.TradeType == TradeType.Rent)
            {
                request.AddContent("propJournal.propJourExt.pay", sortFiled["propJournal.propJourExt.pay"]);
                request.AddContent("propJournal.propJourExt.detain", sortFiled["propJournal.propJourExt.detain"]);
            }
            request.AddContent("propJournal.bedroomCount", sortFiled["propJournal.bedroomCount"]);
            request.AddContent("propJournal.sittingroomCount", sortFiled["propJournal.sittingroomCount"]);

            request.AddContent("propJournal.propJourExt.toiletCount", sortFiled["propJournal.propJourExt.toiletCount"]);
            request.AddContent("propJournal.propJourExt.balconyCount", sortFiled["propJournal.propJourExt.balconyCount"]);
            request.AddContent("propJournal.propJourExt.muchElevator", sortFiled["propJournal.propJourExt.muchElevator"]);
            request.AddContent("propJournal.propJourExt.muchFamily", sortFiled["propJournal.propJourExt.muchFamily"]);
            request.AddContent("propJournal.propJourExt.propertyFloors", sortFiled["propJournal.propJourExt.propertyFloors"]);
            request.AddContent("propJournal.propJourExt.totalFloors", sortFiled["propJournal.propJourExt.totalFloors"]);
            request.AddContent("propJournal.propJourExt.age", sortFiled["propJournal.propJourExt.age"]);

            if (info.TradeType == TradeType.Sale)
            {
                request.AddContent("propJournal.propJourExt.manageFee", sortFiled["propJournal.propJourExt.manageFee"]);
                request.AddContent("propJournal.propJourExt.is5Years", sortFiled["propJournal.propJourExt.is5Years"]);
            }

            request.AddContent("propJournal.propJourExt.orientation", sortFiled["propJournal.propJourExt.orientation"]);
            request.AddContent("propJournal.propJourExt.fitment", sortFiled["propJournal.propJourExt.fitment"]);
            request.AddContent("propJournal.propJourExt.configure", sortFiled["propJournal.propJourExt.configure"]);
            request.AddContent("propJournal.propJourExt.airConditionCount", sortFiled["propJournal.propJourExt.airConditionCount"]);
            request.AddContent("propJournal.propJourExt.buildingStructrue", sortFiled["propJournal.propJourExt.buildingStructrue"]);
            request.AddContent("propJournal.propJourExt.addressDetail", sortFiled["propJournal.propJourExt.addressDetail"]);
            request.AddContent("propJournal.propJourExt.customCode", sortFiled["propJournal.propJourExt.customCode"]);
            request.AddContent("propJournal.title", sortFiled["propJournal.title"]);
            request.AddContent("propJournal.content", sortFiled["propJournal.content"]);
            request.AddContent("selectFont", sortFiled["selectFont"]);
            request.AddContent("FontSize", sortFiled["FontSize"]);
            request.AddContent("propJournal.tags", sortFiled["propJournal.tags"]);
            request.AddContent("selectFont", sortFiled["selectFont"]);
        }

        public override bool AddRentHouse(HouseInfo info, ref string targetID)
        {
            UpdateCurrentStatus(StandardProgress.InitalData);
            //GetCityName(info);
            sortFiled.Clear();
            string error = "";
            try
            {
                //http://admin.mysupa.com/propertyNew/loadPropJournal.do?salesType=S
                if (!CheckLogin())
                {
                    UpdateCurrentStatus(StandardProgress.Failed, "登录失败");
                    return false;
                }
                else
                {
                    string errorInfor = "";
                    if (!CommonCheck(info, false, ref errorInfor))
                    {
                        UpdateCurrentStatus(StandardProgress.Failed, errorInfor);
                        return false;
                    }
                    GetCityID(info.City);
                    //http://admin.mysupa.com/evoprop/createPropJournalInit.do?salesType=S
                    WebRequest request = new WebRequest("http://admin.mysupa.com/evoprop/createPropJournalInit.do?salesType=R");
                    request.Cookies = loginCookies;
                    string ret = request.GetResouceStr();

                    request = new WebRequest("http://admin.mysupa.com/evoprop/createPropJournal.do", FormType.FormUrlEncode, Encoding.UTF8, Encoding.GetEncoding("GB2312"));
                    request.SetHeaderValue("Referer", "http://admin.mysupa.com/evoprop/createPropJournalInit.do?salesType=R");
                    request.SetHeaderValue("", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                    request.Cookies = loginCookies;
                    request.Cookies["Hm_lvt_413e31eb64ce7d19ba4cf37ed4bd0f7e"] = "1347452442161,1347460494287,1347464082841,1347538410182";
                    request.Cookies["__utma"] = "226206277.1753385560.1347375197.1347464083.1347538410.6";
                    request.Cookies["__utmz"] = "226206277.1347538410.6.3.utmcsr=baidu|utmccn=(organic)|utmcmd=organic|utmctr=%E8%B6%85%E7%BA%A7%E7%BB%8F%E7%BA%AA%E4%BA%BA";
                    request.Cookies["userSid"] = "87623606522119021736606";
                    request.Cookies["key"] = CityID;
                    //request.Cookies.Add("mysessionidup", "6fca8c80-2dd5-414a-bb10-35ecc62b9264192.168.30.73");
                    request.Cookies["Hm_lpvt_413e31eb64ce7d19ba4cf37ed4bd0f7e"] = "1347538590146";
                    request.Cookies["__utmb"] = "226206277.5.10.1347538410";
                    request.Cookies["__utmc"] = "226206277";
                    MapUserID(request, ret);
                    if (BuildingMapping(request, info, false, ret))
                    {
                        // string content = request.SendWaitString();
                        FillPostData(request, info, false);
                        UpdateCurrentStatus(StandardProgress.PosData);
                        FillSortedField(info, request);
                        string content = request.SendWaitString();
                        targetID = GetTargetID(content);

                        if (string.IsNullOrEmpty(targetID))
                        {
                            UpdateCurrentStatus(StandardProgress.Failed, "房源发布失败!");
                            return false;
                        }
                        else
                        {
                            SyncImage(info, targetID);
                            string downUrl = "http://admin.mysupa.com/evoimg/saveImageUpload.do?subType=2&journalId=" + targetID;
                            request = new WebRequest(downUrl, FormType.FormUrlEncode);
                            request.SetHeaderValue("Referer", "http://admin.mysupa.com/evoimg/imageUpload.do?journalId=" + targetID);
                            request.AllowRedirect = false;
                            request.Cookies = loginCookies;
                            request.AddContent("videoId", "0");
                            request.AddContent("photoId", "1");
                            if (retImagesUrl.Count > 0)
                            {
                                request.AddContent("coverImage", retImagesUrl[0]);
                            }
                            else
                            {
                                request.AddContent("coverImage", "");
                            }
                            request.AddContent("delImg", "");

                            request.AddContent("textValue", "");
                            request.AddContent("images1", "");
                            request.AddContent("images3", "");
                            string img5 = "";
                            foreach (string img in retImages)
                            {
                                img5 = img5 + img + ":室内图,";
                            }
                            request.AddContent("img5", string.IsNullOrEmpty(img5) ? "0" : img5);
                            request.AddContent("img1", "0");
                            request.AddContent("img3", "0");
                            request.SendWaitString();
                            request = new WebRequest(request.TransferLocation);
                            request.Cookies = loginCookies;
                            ret = request.GetResouceStr();
                            if (ret.Contains("房源发布成功"))
                            {
                                UpdateCurrentStatus(StandardProgress.Sucess, GetImageError(info), targetID, "http://" + CityShort + ".item.mysupa.com/property/" + targetID + ".html");
                                return true;
                            }
                            else
                            {
                                UpdateCurrentStatus(StandardProgress.Failed, "房源发布失败", targetID, "");
                                return false;
                            }

                        }
                    }
                    else
                    {
                        UpdateCurrentStatus(StandardProgress.Failed, "提交出错.网站上可能不存在此小区，请确认后再试！");
                        return false;
                    }
                }
            }
            catch (System.Net.WebException exp)
            {
                error = WebError;
            }
            catch (Exception exp)
            {
                LogCenter.Log("超级经纪人信息提交", exp);
                error = exp.Message;
            }
            UpdateCurrentStatus(StandardProgress.Failed, error);
            return false;
        }

        public override bool DeleteSaleHouse(HouseInfo info, string targetID)
        {
            return InnerDelete(info, targetID, true);
        }

        public override bool DeleteRentHouse(HouseInfo info, string targetID)
        {
            return InnerDelete(info, targetID, false);
        }

        public override bool RefreshSaleHouse(HouseInfo info, string targetID)
        {
            return InnerRefresh(targetID, true);
        }

        private bool InnerRefresh(string targetID, bool isSale)
        {
            UpdateCurrentStatus(StandardProgress.InitalData);
            //GetCityName(info);
            string error = "";
            try
            {
                if (!CheckLogin())
                {
                    UpdateCurrentStatus(StandardProgress.Failed, "登录失败");
                    return false;
                }
                else
                {
                    string saleType = "S";
                    if (isSale)
                    {
                        saleType = "S";
                    }
                    else
                    {
                        saleType = "R";
                    }
                    string str2 = "http://admin.mysupa.com/propertyNewManage/listPropJournal.do?salesType=" + saleType + "&status=1";
                    WebRequest request = new WebRequest(str2);
                    request.Cookies = loginCookies;
                    string ret = request.GetResouceStr();
                    Regex regex = new Regex("<span class=\"fr\" >房源数  <strong>([\\d]*?)</strong>");
                    int sources = Convert.ToInt32(regex.Match(ret).Groups[1].Value);


                    string str4 = "http://admin.mysupa.com/refresh/refreshLeavedCount.do?day=0";
                    request = new WebRequest(str4);
                    request.Cookies = loginCookies;

                    string str5 = request.GetResouceStr();
                    Regex regex2 = new Regex("您今天剩余房源刷新次数：<strong id=\"leaRefresh\">(?<num>[\\S]*?)次</strong>");
                    int num2 = Convert.ToInt32(regex2.Match(str5).Groups[1].Value);

                    DateTime now = DateTime.Now;
                    int result = 2;
                    if (num2 == 0)
                    {
                        UpdateCurrentStatus(StandardProgress.Failed, "刷新量已达到最大，则网站不允许再刷新！");
                        return false;
                    }
                    else
                    {
                        if (CheckHouseExits(isSale, targetID))
                        {
                            for (int i = 0; i < (sources + 1); i += 10)
                            {
                                string url = "http://admin.mysupa.com/propertyNewManage/listPropJournal.do?salesType=" + saleType + "&status=1&maxPageItems=10&maxPageItems=10&maxPageItems=10&maxPageItems=10&maxPageItems=10&maxPageItems=10&maxPageItems=10&maxIndexPages=5&maxIndexPages=5&maxIndexPages=5&maxIndexPages=5&pager.offset=" + i;
                                request = new WebRequest(url);
                                request.Cookies = loginCookies;
                                string str6 = request.GetResouceStr();
                                MatchCollection matchs = new Regex("<input type=\"checkbox\" name=\"id\" value=\"(?<aaa>[\\d]*?)\"/>").Matches(str6);
                                List<string> list = new List<string>();
                                foreach (Match match in matchs)
                                {
                                    list.Add(match.Groups["aaa"].Value.Trim());
                                }
                                string[] strArray = new string[list.Count];
                                for (int j = 0; j < list.Count; j++)
                                {
                                    strArray[j] = list[j].ToString();
                                }
                                UpdateCurrentStatus(StandardProgress.PosData);
                                if (strArray.Length != 0)
                                {
                                    for (int k = 0; k < strArray.Length; k++)
                                    {
                                        if (strArray[k] == targetID)
                                        {

                                            Convert.ToInt32(i.ToString().Substring(0, 1));
                                            url = "http://admin.mysupa.com/propertyNewManage/refreshPropJour.do?flag=prop&pager.offset=" + i;
                                            request = new WebRequest(url, FormType.FormUrlEncode);
                                            request.Cookies = loginCookies;
                                            this.RefreshSiteHouseForm(request, isSale, sources, i, k, strArray);
                                            ret = request.SendWaitString();
                                            UpdateCurrentStatus(StandardProgress.Sucess, "");
                                            return true;
                                        }

                                    }
                                }
                            }
                        }
                        else
                        {
                            UpdateCurrentStatus(StandardProgress.Failed, "网站上不存在此房源");
                            return false;
                        }
                    }

                }
            }
            catch (System.Net.WebException exp)
            {
                error = WebError;
            }
            catch (Exception exp)
            {
                LogCenter.Log("超级经纪人信息刷新异常", exp);
                error = exp.Message;
            }
            UpdateCurrentStatus(StandardProgress.Failed, error);
            return false;
        }
        public override bool RefreshRentHouse(HouseInfo info, string targetID)
        {
            return InnerRefresh(targetID, false);
        }
        #endregion

        #region HelpFunction

        private bool CheckHouseExits(bool isSale, string propertyid)
        {
            string url = "";
            if (isSale)
            {
                url = "http://admin.mysupa.com/propertyNewManage/listPropJournal.do?salesType=S&status=1&maxPageItems=-1";
            }
            else
            {
                url = "http://admin.mysupa.com/propertyNewManage/listPropJournal.do?salesType=R&status=1&maxPageItems=-1";
            }

            WebRequest request = new WebRequest(url);
            request.Cookies = loginCookies;
            string input = request.GetResouceStr();
            Regex regex = new Regex("<td class=\"w87\"><input type=\"checkbox\" name=\"id\" value=\"(?<houseId>[\\d\\s]*?)\"/>");
            foreach (Match match in regex.Matches(input))
            {
                if ((match.Groups["houseId"] != null) && (match.Groups["houseId"].Value.Trim() == propertyid))
                {
                    return true;
                }
            }
            return false;
        }

        private bool InnerDelete(HouseInfo info, string targetID, bool isSale)
        {
            UpdateCurrentStatus(StandardProgress.InitalData);
            try
            {
                if (CheckLogin())
                {

                    string mainUrl = "";
                    string deleteUrl = "";
                    if (isSale)
                    {
                        mainUrl = "http://admin.mysupa.com/propertyNewManage/listPropJournal.do?salesType=S&status=1";
                        deleteUrl = "http://admin.mysupa.com/propertyNewManage/upOrDownPropJournal.do?salesType=S&status=1";
                    }
                    else
                    {
                        mainUrl = "http://admin.mysupa.com/propertyNewManage/listPropJournal.do?salesType=R&status=1";
                        deleteUrl = "http://admin.mysupa.com/propertyNewManage/upOrDownPropJournal.do?salesType=R&status=1";
                    }
                    WebRequest request = new WebRequest(mainUrl);
                    request.Cookies = loginCookies;
                    request.GetResouceStr();

                    request = new WebRequest(deleteUrl, FormType.FormUrlEncode);
                    request.Cookies = loginCookies;
                    DeleteHouseInfor(targetID, isSale, request);

                    UpdateCurrentStatus(StandardProgress.PosData);
                    string ret = request.SendWaitString();
                    ret = HttpUtility.UrlDecode(ret, Encoding.UTF8);
                    if (ret.Contains("房源下架成功"))
                    {
                        UpdateCurrentStatus(StandardProgress.Sucess, "");
                        return true;
                    }
                    UpdateCurrentStatus(StandardProgress.Failed, "删除房源失败");
                    LogCenter.LogMessage("删除失败(超级经纪人),Target:" + targetID + "返回值" + ret);
                    return false;
                }
                else
                {
                    UpdateCurrentStatus(StandardProgress.Failed, "登陆失败");
                    return false;
                }

            }
            catch (System.Net.WebException exp)
            {
                UpdateCurrentStatus(StandardProgress.Failed, WebError);
                return false;
            }
        }

        private static void DeleteHouseInfor(string targetID, bool isSale, WebRequest request)
        {

            string fieldName = "che" + targetID;
            string fieldValue = "";
            if (isSale)
            {
                fieldValue = "0|0|0|0|0|0|0";
            }
            else
            {
                fieldValue = "1|0|0|0|0|0|1";
            }
            request.AddContent("type", "down");
            request.AddContent("pageFlag", "prop");
            request.AddContent("status", "1");
            request.AddContent("salesType", isSale ? "S" : "R");
            request.AddContent("totalItems", "1");
            request.AddContent("setPageItems", "10");
            request.AddContent("pagerOffset", "0");
            request.AddContent("builtArea", "");
            request.AddContent("salePrice", "");
            request.AddContent("bedroomCount", "");
            request.AddContent("sittingroomCount", "");
            request.AddContent("keyword", "请输入房源编号或楼盘名称");
            request.AddContent("order", "1");
            request.AddContent("jid", targetID);
            request.AddContent("id", targetID);
            request.AddContent(fieldName, fieldValue);
            request.AddContent("maxPageItems", "10");
        }
        private void RefreshSiteHouseForm(WebRequest request, bool isSale, int sources, int i, int n, string[] str_refNum)
        {
            request.AddContent("type", "");
            request.AddContent("pageFlag", "prop");
            request.AddContent("status", "1");
            if (isSale)
            {
                request.AddContent("salesType", "S");
            }
            else
            {
                request.AddContent("salesType", "R");
            }
            request.AddContent("totalItems", sources.ToString());
            request.AddContent("setPageItems", "10");
            request.AddContent("pagerOffset", i.ToString());
            request.AddContent("builtArea", "");
            request.AddContent("salePrice", "");
            request.AddContent("bedroomCount", "");
            request.AddContent("sittingroomCount", "");
            request.AddContent("keyword", "请输入房源编号或楼盘名称");
            request.AddContent("order", "1");
            for (int j = 0; j < str_refNum.Length; j++)
            {
                string fieldName = "che" + str_refNum[j];
                if (n == j)
                {
                    request.AddContent("jid", str_refNum[n]);
                    request.AddContent("id", str_refNum[n]);
                    request.AddContent(fieldName, "0|0|0|0|0|0|0");
                }
                else
                {
                    request.AddContent("jid", str_refNum[n]);
                    request.AddContent(fieldName, "0|0|0|0|0|0|0");
                }
            }
            request.AddContent("maxPageItems", "10");
        }


        private void SyncImage(HouseInfo info, string targetID)
        {
            retImages.Clear();
            retImagesUrl.Clear();
            errorImage = 0;
            if (info.Images != null && info.Images.Length > 0)
            {
                string status = "";
                foreach (string url in info.Images)
                {
                    try
                    {
                        WebRequest request = new WebRequest(url);
                        Stream stream = request.GetResouce();
                        string name = url.Substring(url.LastIndexOf('/') + 1);


                        request = new WebRequest("http://admin.mysupa.com/evoimg/ajaxImageUploadFile.do?" + "type=5&numPic=0&journalId=" + targetID, FormType.MultiPart);

                        request.Cookies = loginCookies;
                        request.ReturnEncoding = outputCoding;
                        request.AddContent("picType", "5");//5室内照 1小区 3户型
                        request.AddFile(name, "pic", stream);
                        //request.AddContent("Filename", name);

                        //request.AddContent("journalId", targetID);

                        //request.AddContent("Upload", "Submit Query");

                        string ret = request.SendWaitString();
                        //图片高度有限制 <script>parent.checkImageWidthAndHeight('0','5')</script>

                        GetImages(ret);
                    }
                    catch
                    {
                        errorImage++;
                    }
                    //retImages.Add(img);
                }
            }
        }

        private void GetImages(string imgString)
        {
            try
            {
                if (imgString.Contains("img") && imgString.Contains("经纪人"))
                {
                    Regex regex = new Regex(@"\d,(?<imgUrl>[\S\s]*?),(?<imgId>[\d\s]*?),经纪人");
                    if (regex.IsMatch(imgString))
                    {
                        Match match = regex.Match(imgString);
                        if ((match.Groups["imgUrl"] != null) && (match.Groups["imgId"] != null))
                        {
                            retImages.Add(match.Groups["imgId"].Value.Trim());
                            retImagesUrl.Add("http://pic.mysupa.com/" + match.Groups["imgUrl"].Value.Trim());
                            //str = match.Groups["imgId"].Value.Trim() + "~http://pic.mysupa.com/" + match.Groups["imgUrl"].Value.Trim();
                        }
                        else
                        {
                            errorImage++;
                        }
                    }
                    Regex regex2 = new Regex(@",[\S\s]*?,[\d\s]*?,(?<title>[\S\s]*?),(?<flag>[\d\s]*?),(?<path>[\S\s]*?),");
                    if (regex2.IsMatch(imgString))
                    {
                        string str2 = "";
                        str2 = "http://admin.mysupa.com/evoimg/ajaxCompressPic.do";
                        string str3 = "";
                        string str4 = "";
                        string str5 = "";

                        Match match2 = regex2.Match(imgString);
                        if (match2.Groups["title"] != null)
                        {
                            str3 = match2.Groups["title"].Value.Trim() ?? "";
                        }
                        if (match2.Groups["flag"] != null)
                        {
                            str4 = match2.Groups["flag"].Value.Trim() ?? "";
                        }
                        if (match2.Groups["path"] != null)
                        {
                            str5 = match2.Groups["path"].Value.Trim() ?? "";
                        }
                        str2 = ((str2 + "?title=" + HttpUtility.UrlPathEncode(str3)) + "&flag=" + str4) + "&path=" + str5;
                        try
                        {
                            WebRequest request = new WebRequest(str2);
                            request.Cookies = loginCookies;
                            request.GetResouceStr();//为了Cookies.
                        }
                        catch
                        { }
                    }
                }
            }
            catch (Exception exp)
            {
                LogCenter.Log("发布图片出现异常.超级经纪人", exp);
            }
        }



        private string GetTargetID(string strHtml)
        {
            //<br/><script type="text/javascript"> parent.evoProp.createResp('1','23703986')</script>
            string str = "";
            try
            {
                if (strHtml.Contains("evoProp.createResp"))
                {
                    Regex regex = new Regex(@"createResp\('\d*?','(?<hid>[\d\s]*?)'\)");
                    if (regex.IsMatch(strHtml))
                    {
                        Match match = regex.Match(strHtml);
                        if ((match.Groups["hid"] != null) && ((match.Groups["hid"].Value.Trim() ?? "") != ""))
                        {
                            return match.Groups["hid"].Value.Trim();
                        }
                    }
                }
                return str;
            }
            catch (Exception exception)
            {
                LogCenter.Log("获取返回TargetID出错。超级经纪人", exception);

            }
            return str;
        }




        private bool BuildingMapping(WebRequest request, HouseInfo info, bool IsSale, string html)
        {
            string tradeType = "S";
            if (!IsSale)
            {
                tradeType = "Z";
            }
            string ret = MapEstate(tradeType, info);
            if (!string.IsNullOrEmpty(ret))
            {
                string[] strArray = ret.Replace("s0.", "|").Split(new char[] { '|' });
                if (strArray.Length >= 25)
                {
                    AddContent("propJournal.propRelation.areaId", GetFirstEle(strArray[5]));
                    AddContent("avgPrice", GetFirstEle(strArray[15]));
                    AddContent("propJournal.address", HtmlHelper.DecodingJSON(GetFirstEle(strArray[18])));
                    AddContent("propJournal.propJourExt.addressDetail", "");
                    AddContent("propJournal.propRelation.subAreaId", GetFirstEle(strArray[21]));
                    AddContent("propJournal.propertyName", HtmlHelper.DecodingJSON(GetFirstEle(strArray[24])));
                    //AddContent("cityId", this.GetFirstEle(strArray[26]));
                    AddContent("propJournal.propRelation.estateId", this.GetFirstEle(strArray[27]));
                    return true;
                }
            }
            string distict = "";
            if (info.LocalDistrict == "浦东")
            {
                distict = "浦东新区";
            }
            else
            {
                distict = info.LocalDistrict;
            }

            Regex reg = new Regex(@"<option value=""(?<districtID>\d*)"">" + distict + "</option>");
            Match ma = reg.Match(html);

            AddContent("propJournal.propRelation.estateId", "0");
            AddContent("avgPrice", "0");
            AddContent("propJournal.address", info.LocalAddress);
            AddContent("propJournal.propJourExt.addressDetail", "");
            AddContent("propJournal.propertyName", info.Estate);
            if (ma.Success)
            {

                string districtID = ma.Groups["districtID"].Value;
                AddContent("propJournal.propRelation.areaId", districtID);
                WebRequest diduanRequest = new WebRequest(string.Format("http://admin.mysupa.com/images/statistics/ajax/?url=sub_area/publish_html/{0}area.html", districtID));
                diduanRequest.Cookies = loginCookies;
                string diduanRet = diduanRequest.GetResouceStr();
                Regex diduanReg = new Regex(@"(?<diduanID>\d*):" + info.LocalDiduan);
                Match diduanMa = diduanReg.Match(diduanRet);
                if (diduanMa.Success)
                {
                    AddContent("propJournal.propRelation.subAreaId", diduanMa.Groups["diduanID"].Value);
                }
                else
                {
                    throw new UnFindDiduanException(info.LocalDiduan);
                }
            }
            else
            {
                throw new UnFindDistrictException(distict);
            }
            LogCenter.LogMessage("未能匹配小区(超级经纪人)　合发码:" + info.HefaCode);
            return true;
        }
        public string GetFirstEle(string input)
        {
            return input.Split(new char[] { '"' })[1];
        }

        private string MapEstate(string houseType, HouseInfo info)
        {
            string str = HtmlHelper.UrlEncode(info.Estate, inputCoding);

            string fieldValue = "string:" + str;
            string str3 = "string:" + CityID;
            WebRequest request = new WebRequest("http://admin.mysupa.com/script/util/call/plaincall/ajaxComm.getAutoCompleteList.dwr", FormType.FormUrlEncode);
            request.Cookies = loginCookies;
            request.AddContent("NoMining1", "1");
            request.AddContent("callCount", "1");
            //request.AddContent("page=/propertyNew/loadPropJournal.do?salesType", houseType);
            request.AddContent("httpSessionId", "abcuiPnP3ETG2anNp-YSs");
            request.AddContent("scriptSessionId", "68C1C8431C55048BE22D42F8CEBDAD5F869");
            request.AddContent("c0-scriptName", "ajaxComm");
            request.AddContent("c0-methodName", "getAutoCompleteList");
            request.AddContent("c0-id", "0");
            request.AddContent("c0-param0", str3);
            request.AddContent("c0-param1", fieldValue);
            request.AddContent("c0-param2", "number:0");
            request.AddContent("c0-param3", "number:6");
            request.AddContent("batchId", "0");
            string ret = request.SendWaitString();
            return ret;
        }

        public void GetCityID(string cityname)
        {
            //通过下边连接获取到的
            //http://u.mysupa.com/user/toRegisterIagent.do?cityId=10
            CityShort = PinyingConvert.Convert(cityname).ToLower();
            switch (cityname)
            {
                case "北京":
                    CityID = "10";
                    break;
                case "广州":
                    CityID = "20";
                    break;
                case "上海":
                    CityID = "21";
                    break;
                case "天津":
                    CityID = "22";
                    break;
                case "重庆":
                    CityID = "23";
                    break;
                case "南京":
                    CityID = "25";
                    break;
                case "武汉":
                    CityID = "27";
                    break;
                case "成都":
                    CityID = "28";
                    break;
                case "石家庄":
                    CityID = "311";
                    break;
                case "大连":
                    CityID = "411";
                    break;
                case "杭州":
                    CityID = "571";
                    break;
                case "宁波":
                    CityID = "574";
                    break;
                case "长沙":
                    CityID = "731";
                    break;
                case "深圳":
                    CityID = "755";
                    break;
                case "佛山":
                    CityID = "757";
                    break;
                case "771":
                    CityID = "771";
                    break;
                default:
                    CityID = "21";
                    break;
            }
        }

        private void FillPostData(WebRequest request, HouseInfo info, bool isSale)
        {

            if (!isSale)
            {
                AddContent("propJournal.salesType", "R");
                AddContent("propJournal.priceType", "2");
                AddContent("temp_rentPrice", string.IsNullOrEmpty(info.MonthPrice) ? "0" : info.Price);
                FillHouseType(info, request);
                FillPayType(info, request);

            }
            else
            {
                AddContent("propJournal.salesType", "S");
                AddContent("propJournal.priceType", "1");
                FillHouseType(info, request);
                AddContent("temp_salePrice", string.IsNullOrEmpty(info.Price) ? "0" : info.Price);
                AddContent("propJournal.propJourExt.manageFee", "");

                int age = 2010;
                int.TryParse(info.Age, out age);
                if ((DateTime.Now.Year + 1 - age) >= 5)
                {
                    AddContent("propJournal.propJourExt.is5Years", "1");
                }
                else
                {
                    AddContent("propJournal.propJourExt.is5Years", "0");
                }

            }
            AddContent("propJournal.propJourExt.configure", "");
            AddContent("propJournal.salePrice", ConvertToFloat(info.Price));

            AddContent("propJournal.rentPrice", string.IsNullOrEmpty(info.MonthPrice) ? "0" : info.MonthPrice);
            AddContent("cityId", CityID);
            AddContent("propJournal.status", "2");

            AddContent("propJournal.bedroomCount", info.Room);
            AddContent("propJournal.sittingroomCount", info.Hall);
            AddContent("propJournal.propJourExt.toiletCount", info.WashRoom);
            AddContent("propJournal.propJourExt.balconyCount", "0");

            AddContent("propJournal.propJourExt.muchElevator", "");
            AddContent("propJournal.propJourExt.muchFamily", "");
            AddContent("propJournal.propJourExt.propertyFloors", info.CurrentFloor);
            AddContent("propJournal.propJourExt.totalFloors", info.Floors);
            AddContent("propJournal.propJourExt.age", info.Age);

            AddContent("propJournal.propJourExt.spaceHeight", "");

            AddContent("propJournal.propJourExt.orientation", GetToward(info));
            AddContent("propJournal.propJourExt.fitment", GetDecoration(info));
            AddContent("propJournal.propJourExt.buildingStructrue", "1");
            AddContent("propJournal.propJourExt.airConditionCount", "");
            AddContent("propJournal.propJourExt.serialCode", "");
            AddContent("propJournal.propJourExt.customCode", "");
            AddContent("propJournal.title", info.Title);
            AddContent("propJournal.content", info.Description);
            AddContent("theUrl", "http://");

            AddContent("stopComUse", "0");
            AddContent("plotFlag", "0");
            AddContent("jumpKey", "p");
            //AddContent("cityId", "p");
            AddContent("selectFont", "宋体");
            AddContent("FontSize", "4");

            AddContent("propJournal.builtArea", info.Area);

        }

        private void MapUserID(WebRequest request, string strHtml)
        {
            try
            {
                string str = "";
                if (((strHtml ?? "") != "") && strHtml.Contains("propJournal.userId"))
                {
                    Regex regex = new Regex("<input type=\"hidden\" name=\"propJournal.userId\" id=\"propJournal.userId\" value=\"(?<userId>[\\d\\s]*?)\"\\s*?/>");
                    if (regex.IsMatch(strHtml))
                    {
                        Match match = regex.Match(strHtml);
                        if (match.Groups["userId"] != null)
                        {
                            str = match.Groups["userId"].Value ?? "";
                        }
                    }
                }
                AddContent("propJournal.userId", str);
            }
            catch (Exception exp)
            {
                LogCenter.Log("超级经纪人查找用户ID", exp);
            }
        }

        public void FillHouseType(HouseInfo info, WebRequest request)
        {
            //当前 房屋类型.平房=1,普通住宅=2,商住两用=3,公寓=4,别墅=5,其他=6
            //目标 普通住宅 =Z,公寓=G,商铺=S,别墅=B,写字楼=X,仓库厂房=C,车位=P

            string type = "Z";
            switch (info.HouseType)
            {
                case "1":
                case "2":
                case "3":
                case "6":
                    type = "Z";
                    break;
                case "4":
                    type = "G";
                    break;
                case "5":
                    type = "B";
                    break;
                default:
                    break;
            }
            AddContent("propJournal.propertyType", type);
            AddContent("bakPropertyType", "");
            AddContent("propJournal.tags", "76,有钥即看");
        }
        public string GetHouseType(HouseInfo info)
        {

            string type = "Z";
            switch (info.HouseType)
            {
                case "1":
                case "2":
                case "3":
                case "6":
                    type = "Z";
                    break;
                case "4":
                    type = "G";
                    break;
                case "5":
                    type = "B";
                    break;
                default:
                    break;
            }
            return type;
        }

        private void FillPayType(HouseInfo info, WebRequest request)
        {
            //当前 1:付一押一 2:付二押一 3:付三押一 4:付六押一
            string pay = "1";
            string detain = "1";
            switch (info.PayType)
            {
                case "1":
                    pay = "1";
                    detain = "1";
                    break;
                case "2":
                    pay = "2";
                    detain = "1";
                    break;
                case "3":
                    pay = "3";
                    detain = "1";
                    break;
                case "4":
                    pay = "6";
                    detain = "1";
                    break;
                default:
                    pay = "3";
                    detain = "1";
                    break;
            }
            AddContent("propJournal.propJourExt.pay", pay);
            AddContent("propJournal.propJourExt.detain", detain);
        }

        private void GetPayType(HouseInfo info, out string pay, out string detain)
        {
            //当前 1:付一押一 2:付二押一 3:付三押一 4:付六押一
             pay = "1";
             detain = "1";
            switch (info.PayType)
            {
                case "1":
                    pay = "1";
                    detain = "1";
                    break;
                case "2":
                    pay = "2";
                    detain = "1";
                    break;
                case "3":
                    pay = "3";
                    detain = "1";
                    break;
                case "4":
                    pay = "6";
                    detain = "1";
                    break;
                default:
                    pay = "3";
                    detain = "1";
                    break;
            }
        }

        public string GetDecoration(HouseInfo dec)
        {
            //当前 1:毛胚 2:简装 3:精装 4:豪装
            //目标 豪华装修, 精致装修 , 中等装修 , 简单装修 , 毛坯
            switch (dec.Decoration)
            {
                case "1":
                    return "毛坯";
                case "2":
                    return "简单装修";
                case "3":
                    return "精致装修";
                case "4":
                    return "豪华装修";
                default:
                    return "简单装修";
            }
        }

        private string ConvertToFloat(string input)
        {
            if (!input.Contains("."))
            {
                return input + ".00";
            }
            return input;
        }

        private string GetToward(HouseInfo info)
        {
            //当前 东=1,南=2, 西=3,北=4,南北=5,东西=6,东南=7,西南=8,东北=9,西北=10,不知道朝向=11
            //目标: 汉字
            switch (info.Toward)
            {
                case "1":
                    return "东";
                case "2":
                    return "南";
                case "3":
                    return "西";
                case "4":
                    return "北";
                case "5":
                    return "南北";
                case "6":
                    return "东西";
                case "7":
                    return "东南";
                case "8":
                    return "西南";
                case "9":
                    return "东北";
                case "10":
                    return "西北";
                default:
                    return "南";
            }
        }

        private void AddContent(string _key, string _value)
        {
            sortFiled.Add(_key, _value);
        }
        #endregion

        #region 编辑功能
        public override bool OpenEidt(WebBrowserOp op, HouseInfo info)
        {
            try
            {
                if (CheckLogin())
                {
                    if (info.TradeType == TradeType.Sale)
                    {
                        string post = "http://admin.mysupa.com/evoprop/createPropJournalInit.do?salesType=S";
                        foreach (KeyValuePair<string, string> k in loginCookies)
                        {
                            WebBrowserOp.InternetSetCookie(post, k.Key, k.Value);
                        }
                        op.HouseInformation = info;
                        op.Navigate(post);
                        op.Completed += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(op_Sale_Completed);
                    }
                    else
                    {
                        string post = "http://admin.mysupa.com/evoprop/createPropJournalInit.do?salesType=R";
                        foreach (KeyValuePair<string, string> k in loginCookies)
                        {
                            WebBrowserOp.InternetSetCookie(post, k.Key, k.Value);
                        }
                        op.HouseInformation = info;
                        op.Navigate(post);
                        op.Completed += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(op_Rent_Completed);
                    }

                }
                else
                {
                    return false;
                }
            }
            catch
            {
                op.Navigate("http://sh.mysupa.com/");
            }
            return true;
        }
        void op_Sale_Completed(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowserOp cl = sender as WebBrowserOp;
            HouseInfo info = cl.HouseInformation;
            cl.SelectByID_Value("propJournal.propertyType", GetHouseType(info));

            cl.SetValueByID("propJournal.propertyName", info.Estate);

            string estate = info.Estate;
            if (estate == "浦东")
            {
                estate = "浦东新区";
            }
            cl.SelectByName_Text("areaId", estate);

            cl.SetValueByID("propJournal.address", info.LocalAddress);

            cl.SetValueByID("propJournal.builtArea", info.Area);

            cl.SetValueByID("temp_salePrice", info.Price);

            

            cl.SetValueByID("propJournal.bedroomCount", info.Room);
            cl.SetValueByID("propJournal.sittingroomCount", info.Hall);
            cl.SetValueByID("propJournal.propJourExt.toiletCount", info.WashRoom);

            cl.SetValueByID("propJournal.propJourExt.propertyFloors", info.CurrentFloor);
            cl.SetValueByID("propJournal.propJourExt.totalFloors", info.Floors);
            cl.SetValueByID("propJournal.propJourExt.age", info.Age);

            cl.CheckByName_Value("propJournal.propJourExt.orientation", GetToward(info), true);
            cl.CheckByName_Value("propJournal.propJourExt.fitment", GetDecoration(info), true);

            cl.SetValueByID("propJournal.title", info.Title);
            cl.SetCKEditorHtml("bjk_message_jim",info.Description);
        }
        void op_Rent_Completed(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowserOp cl = sender as WebBrowserOp;
            HouseInfo info = cl.HouseInformation;
            cl.SelectByID_Value("propJournal.propertyType", GetHouseType(info));

            cl.SetValueByID("propJournal.propertyName", info.Estate);

            string estate = info.Estate;
            if (estate == "浦东")
            {
                estate = "浦东新区";
            }
            cl.SelectByName_Text("areaId", estate);

            cl.SetValueByID("propJournal.address", info.LocalAddress);

            cl.SetValueByID("propJournal.builtArea", info.Area);
            cl.SetValueByID("temp_rentPrice", info.MonthPrice);

            string pay = "";
            string deposite = "";
            GetPayType(info, out pay, out deposite);

            cl.SetValueByID("propJournal.propJourExt.pay",pay);
            cl.SetValueByID("propJournal.propJourExt.detain", deposite);

            cl.SetValueByID("propJournal.bedroomCount", info.Room);
            cl.SetValueByID("propJournal.sittingroomCount", info.Hall);
            cl.SetValueByID("propJournal.propJourExt.toiletCount", info.WashRoom);

            cl.SetValueByID("propJournal.propJourExt.propertyFloors", info.CurrentFloor);
            cl.SetValueByID("propJournal.propJourExt.totalFloors", info.Floors);
            cl.SetValueByID("propJournal.propJourExt.age", info.Age);

            cl.CheckByName_Value("propJournal.propJourExt.orientation", GetToward(info),true);

            cl.SetValueByID("propJournal.title", info.Title);
            cl.SetCKEditorHtml("bjk_message_jim" ,info.Description);
        }
        #endregion
    }
}
